<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="表名" prop="tableName">
        <el-input
          v-model.trim="queryParams.tableName"
          placeholder="请输入表名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="表异常数据id" prop="exceptionDataId">
        <el-input
          v-model.trim="queryParams.exceptionDataId"
          placeholder="请输入表异常数据id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="标签名称" prop="tagName">
        <el-input
          v-model.trim="queryParams.tagName"
          placeholder="请输入标签名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="逻辑删除" prop="isDelete">
        <el-input
          v-model.trim="queryParams.isDelete"
          placeholder="请输入逻辑删除"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['abnormal:BiAbnormalData:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['abnormal:BiAbnormalData:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['abnormal:BiAbnormalData:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['abnormal:BiAbnormalData:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button size="mini" plain icon="el-icon-upload" @click="daoru"
          >文件数据比对</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="BiAbnormalDataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="表名" align="center" prop="tableName" />
      <el-table-column
        label="表异常数据id"
        align="center"
        prop="exceptionDataId"
      />
      <el-table-column label="异常描述" align="center" prop="tagName" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <!-- <el-table-column label="逻辑删除" align="center" prop="isDelete" /> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['abnormal:BiAbnormalData:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['abnormal:BiAbnormalData:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改异常数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="表名" prop="tableName">
          <el-input v-model.trim="form.tableName" placeholder="请输入表名" />
        </el-form-item>
        <el-form-item label="表异常数据id" prop="exceptionDataId">
          <el-input
            v-model.trim="form.exceptionDataId"
            placeholder="请输入表异常数据id"
          />
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model.trim="form.tagName" placeholder="请输入标签名称" />
        </el-form-item>
        <!-- <el-form-item label="逻辑删除" prop="isDelete">
          <el-input v-model.trim="form.isDelete" placeholder="请输入逻辑删除" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改产品二级信息对话框 -->
    <el-dialog
      title="导入"
      :visible.sync="dialogVisible"
      width="600px"
      append-to-body
      v-if="dialogVisible"
    >
      <!-- 文件上传-->
      <el-form
        :rules="rules"
        :model="dataForm"
        ref="dataForm"
        label-width="100px"
        @submit.native.prevent
      >
        <el-form-item label="文件：" prop="file">
          <el-upload
            class="upload-import"
            ref="upload"
            :http-request="uploadFile"
            action=""
            :on-remove="handleRemove"
            :file-list="fileList"
            :limit="2"
            :on-change="handleChange"
            :auto-upload="false"
            :before-upload="beforeAvatarUpload"
            multiple
          >
            <!--
            accept="application/zip,.zip" 设置接收的文件类型-->
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
            <!-- <div slot="tip" class="el-upload__tip">
          只能上传zip文件，且不超过10M
        </div> -->
          </el-upload>
          <!-- 关闭自动上传-->
        </el-form-item>
        <el-form-item label="文件1：" prop="file">
          <el-input
            v-model="dataForm.fileKey1"
            placeholder="多主键情况下，用，隔开"
            clearable
            style="width: 200px"
          />
          <el-input
            v-model="dataForm.fileValue1"
            placeholder="文件1值"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="文件2：" prop="file">
          <el-input
            v-model="dataForm.fileKey2"
            placeholder="多主键情况下，用，隔开"
            clearable
            style="width: 200px"
          />
          <el-input
            v-model="dataForm.fileValue2"
            placeholder="文件2值"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <!-- <el-form-item label="店铺：" prop="name">
         
          <el-cascader
            class="region"
            v-model="dataForm.name"
            placeholder="选择店铺分组"
            :options="cascadeList"
            :props="{ checkStrictly: true }"
            style="width: 300px; height: 30px"
            @change="changecascadeList"
          >
          </el-cascader>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
          <el-button @click="dialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      title="导入结果"
      :visible.sync="openDataCheck"
      width="1000px"
      append-to-body
      v-if="openDataCheck"
    >
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExportCheck"
          >导出</el-button
        >
      </el-col>
      <el-table
        :data="DataCheck"
        @selection-change="handleSelectionChangeExport"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="A值" align="center" prop="A值" />
        <el-table-column label="B值" align="center" prop="B值" />
        <el-table-column label="键值" align="center" prop="键值" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBiAbnormalData,
  getBiAbnormalData,
  delBiAbnormalData,
  addBiAbnormalData,
  updateBiAbnormalData,
  importDataCheck,
} from "@/api/abnormal/BiAbnormalData";
import axios from "axios";
//--------导入token
import { getToken } from "@/utils/auth";
export default {
  name: "BiAbnormalData",
  data() {
    return {
      list: [],
      openDataCheck: false,
      DataCheck: [],
      formDate: "", //载体
      dataForm: {
        name: [],
        file: null,
      },
      hasFile: false,
      fileList: [],
      dialogVisible: false,
      pjtUrl: process.env.VUE_APP_BASE_API,
      rules: {
        name: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { max: 50, message: "最长可输入50个字符", trigger: "blur" },
          // { validator: isvalidatName, trigger: "blur" },
        ],
        file: [{ required: true, message: "请选择上传文件", trigger: "blur" }],
      },

      inputValue: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 异常数据表格数据
      BiAbnormalDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tableName: null,
        exceptionDataId: null,
        tagName: null,
        isDelete: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //图片上传前的相关判断
    beforeAvatarUpload(file) {
      // const isJPG = file.type == 'image/jpeg' || file.type == 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 100;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error("上传导入文件大小不能超过 100MB!");
      }

      return isLt2M;
    },
    handleRemove(file, fileList) {
      if (!fileList.length) {
        this.hasFile = false;
      }
      this.dataForm.file = null;
    },
    handleChange(file, fileList) {
      if (fileList.length > 2) {
        return;
      }
      // if (fileList.length === 1) {
      //   this.hasFile = true;
      // }
      console.log(JSON.stringify(file));
      this.dataForm.file = file;
    },
    //确定按钮
    //调用组件upload的submit方法，从而触发httpRequest方法，实现手动上传
    submitUpload() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$refs.uploadImport.submit();
        }
      });
    },
    uploadFile(file) {
      console.log(JSON.stringify(file));
      //参数file文件就是传入的文件流，添加进formDate中
      this.formDate.append("file", file.file);
    },
    onSubmit() {
      this.formDate = new FormData(); //初始化定义
      this.$refs.upload.submit(); //内部会循环submit，有多少文件就循环几次，每次submit会执行uploadFile方法
      // let obj=
      //   return;
      //submit了之后就可以直接将formData当作参数传给服务器
      //我这里是一个调用api的例子，根据你们实际接口来
      console.log(JSON.stringify(this.formDate));
      this.formDate.append("fileKey1", this.dataForm.fileKey1);
      this.formDate.append("fileKey2", this.dataForm.fileKey2);
      this.formDate.append("fileValue1", this.dataForm.fileValue1);
      this.formDate.append("fileValue2", this.dataForm.fileValue2);
      // importDataCheck(this.formDate).then((response) => {});
      // return;

      // ?fileKey1=" +
      //       this.formDate.fileKey1 +
      //       "&fileKey2=" +
      //       JSON.stringify(this.dataForm.fileKey2) +
      //       "&fileValue1=" +
      //       JSON.stringify(this.dataForm.fileValue1) +
      //       "&fileValue2=" +
      //       JSON.stringify(this.dataForm.fileValue2),
      this.openLoading();
      axios
        .post(
          process.env.VUE_APP_BASE_API +
            "/abnormal/BiAbnormalData/importDataCheck",
          this.formDate,
          {
            headers: {
              header: { responseType: "blob" },

              Authorization: "Bearer " + getToken(),
              "Content-Type": "multipart/form-data",
            }, //定义内容格式,很重要
            // timeout: 20000,
          }
        )
        .then((response) => {
          // this.$modal.closeLoading();
          // console.log(response);
          // if (response.data.code == 200) {
          this.dialogVisible = false;

          //   this.$modal.msgSuccess("导入成功");
          //   // this.hasFile = false;
          //   // this.getList();
          // } else {
          //   this.$modal.msgError("导入失败");
          // }

          this.DataCheck = response.data;
          this.$modal.closeLoading();
          this.openDataCheck = true;
        });
    },

    httpRequest(param) {
      // if (this.dataForm.name.length < 2) {
      //   this.$modal.msgWarning("请选择到渠道");
      //   return;
      // }
      let fd = new FormData();
      fd.append("file", param.file); // 传文件
      fd.append("salesGrade", this.dataForm.name);
      // fd.append("brand", this.dataForm.name[0]);
      // fd.append("channel", this.dataForm.name[1]);
      //dataPar.file.raw
      console.log(JSON.stringify(fd));
      return;
      this.openLoading();
      axios
        .post(
          process.env.VUE_APP_BASE_API + "/live/BiLiveTalent/importData",
          fd,
          {
            headers: {
              header: { responseType: "blob" },

              Authorization: "Bearer " + getToken(),
              "Content-Type": "multipart/form-data",
            }, //定义内容格式,很重要
            // timeout: 20000,
          }
        )
        .then((response) => {
          this.$modal.closeLoading();
          console.log(response);
          if (response.data.code == 200) {
            this.dialogVisible = false;

            this.$modal.msgSuccess("导入成功");
            this.hasFile = false;
            this.getList();
          } else {
            this.$modal.msgError("导入失败");
          }
        });
    },
    changecascadeList(value) {
      console.log(JSON.stringify(value));
    },
    //部门文件导入修改打开
    daoru() {
      this.dialogVisible = true;
    },
    // 打开加载层
    openLoading() {
      this.$modal.loading("正在导入，请稍候！");
    },

    /** 查询异常数据列表 */
    getList() {
      this.loading = true;
      listBiAbnormalData(this.queryParams).then((response) => {
        this.BiAbnormalDataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tableName: null,
        exceptionDataId: null,
        tagName: null,
        createTime: null,
        updateTime: null,
        isDelete: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加异常数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBiAbnormalData(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改异常数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBiAbnormalData(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBiAbnormalData(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除异常数据编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBiAbnormalData(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "abnormal/BiAbnormalData/export",
        {
          ...this.queryParams,
        },
        `BiAbnormalData_${new Date().getTime()}.xlsx`
      );
    },
    handleSelectionChangeExport(selection) {
      this.list = selection.map((item) => item);
      console.log(JSON.stringify(this.list));
    },
    /** 导出按钮操作 */
    handleExportCheck() {
      let checklist = [];
      if (this.list.length > 0) {
        checklist = this.list;
      } else {
        checklist = this.DataCheck;
      }
      this.downloadformData(
        "abnormal/BiAbnormalData/exportCheckData",
        checklist,
        `BiAbnormalData_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
